/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.anny.fileuse.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.anny.utils.AttachUtils;
import com.jeeplus.modules.sys.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.anny.fileuse.entity.Attachment;
import com.jeeplus.modules.anny.fileuse.mapper.AttachmentMapper;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 文档汇总类Service
 * @author 林永枝
 * @version 2018-10-18
 */
@Service
@Transactional(readOnly = true)
public class AttachmentService extends CrudService<AttachmentMapper, Attachment> {
	@Autowired
	private AttachmentMapper attachmentMapper;

	public Attachment get(String id) {
		return super.get(id);
	}
	
	public List<Attachment> findList(Attachment attachment) {
		return super.findList(attachment);
	}

	public List<Attachment> findListByforeignAndType(String userOrProductId ,String billType){
		Map<String,Object> paramMap=new HashMap<>();
		paramMap.put("ascriptionId",userOrProductId);
		paramMap.put("fileType",billType);
		return attachmentMapper.findListByforeignAndType(paramMap);
	}
	
	public Page<Attachment> findPage(Page<Attachment> page, Attachment attachment) {
		return super.findPage(page, attachment);
	}
	
	@Transactional(readOnly = false)
	public void save(Attachment attachment) {
		super.save(attachment);
	}
	
	@Transactional(readOnly = false)
	public void delete(Attachment attachment) {
		super.delete(attachment);
	}
	/**
	 * 批量插入附件表
	 * @param attachmentList
	 */
	@Transactional(readOnly = false)
	public void batchInsert(List<Attachment> attachmentList){
		attachmentMapper.batchInsert(attachmentList);
	}

	/**
	 *根据id删除附件
	 *   @param idList
	 */
	@Transactional
	public void deleteByIdList(List<String> idList){
		attachmentMapper.deleteByIdList(idList);
	}
	public void updateAttach(String delAttachId, MultipartFile[] files, String UserOrProductId, String formType){
		//删除前台已删除的附件
		List<String> ids  = Arrays.asList(delAttachId.split(","));
		deleteByIdList(ids);
		//上传附件
		try {
			List<Map<String,Object>> mapList =  fileUpload(Arrays.asList(files), UserOrProductId);
			List<Attachment> attachList = AttachUtils.getAttachments(mapList,UserOrProductId, formType);
			if(attachList.size()>0){
				batchInsert(attachList);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 多文件上传
	 * @param multipartFile
	 * @param UserOrProductId 用户或者商品的id
	 * @return
	 * @throws IOException
	 */
	public List<Map<String,Object>> fileUpload(List<MultipartFile> multipartFile,String UserOrProductId) throws IOException {
		List<Map<String,Object>> paramList = new ArrayList<>();//
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String root=request.getSession().getServletContext().getRealPath("/");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		String year = sdf.format(new Date());
		String  fileDir = DictUtils.getDictLabel("1", AttachUtils.DICT_FILE_UPLOAD_PATH,"C:\\caseFiles");
		fileDir+="\\"+year+"\\"+UserOrProductId+"\\";
		if (null != multipartFile) {
			for (MultipartFile file : multipartFile) {
				if(StringUtils.isEmpty(file.getOriginalFilename())){
					continue;
				}
				String dir = fileDir;
				String fileName = file.getOriginalFilename();// 原文件名称
				String prefix=fileName.substring(fileName.lastIndexOf("."));
				String newFileName = IdGen.uuid()+prefix;
				if(StringUtils.isEmpty(fileName)){
					continue;
				}
				File directory = new File( dir);
				if (!directory.exists()) {
					// 创建目录
					boolean result = directory.mkdirs();
					if (!result) {
						logger.error("创建目录失败！");
					}
				}
				FileCopyUtils.copy(file.getBytes(),
						new FileOutputStream(dir + newFileName));
				Map<String,Object> param = new HashMap<>();
				param.put("realName",fileName);
				param.put("fileName",newFileName);
				param.put("realPath",dir);
				paramList.add(param);
			}
		}
		return paramList;
	}
	
}